package com.weitu.shiro;

import com.weitu.permission.resource.service.ResourceService;
import com.weitu.permission.user.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.Ini;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;


/**
 * 产生责任链，确定每个url的访问权限
 */
public class ChainDefinitionSectionMetaSource implements FactoryBean<Ini.Section> {

    // 静态资源访问权限
    private String filterChainDefinitions;

    private final ResourceService resourceService;

    @Autowired
    public ChainDefinitionSectionMetaSource(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

    public Ini.Section getObject() throws Exception {
        Ini ini = new Ini();
        // 加载默认的url
        ini.load(filterChainDefinitions);

        Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);


        List<Map> mapList = resourceService.selectAllResourcesByUserId(null, null);

        for (Map map : mapList) {
            String code = map.get("code").toString();
            String resUrl = map.get("resUrl").toString();
            String permission = "perms[" + code + "]";
            section.put("/" + resUrl, permission);
        }


        return section;
    }

    @Override
    public Class<?> getObjectType() {
        return this.getClass();
    }

    @Override
    public boolean isSingleton() {
        return false;
    }


    public String getFilterChainDefinitions() {
        return filterChainDefinitions;
    }

    public void setFilterChainDefinitions(String filterChainDefinitions) {
        this.filterChainDefinitions = filterChainDefinitions;
    }
}
